from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

from .antd_page_element import AntdPageElement
from ...common.element_function import ElementFunction
from ...exception.TestException import TestException
from ...exception.errorcode import ErrorCode


class Tabs(AntdPageElement):
    def setValue(self, value):
        self.wait_element_presence()
        # TODO: slide类形的会有问题, 只能获取到当前显示的Tab值
        # self._scroll_to_end()
        tab_elements = self._find_tab_elements()

        for tab_element in tab_elements:
            if self._get_tab_title(tab_element) == value:
                ElementFunction(self._driver).click(tab_element)
                if not self._is_checked(tab_element):
                    raise TestException.by_error_code(ErrorCode.ELEMENT_OPERATE_FAILED,
                                                      message='tab {0} selected failed'.format(value))
                break
        else:
            raise TestException.by_error_code(ErrorCode.VALUE_NOT_FIND,
                                              value='tab {0}'.format(value))

    def click(self, tab_title):
        self.setValue(tab_title)

    def _scroll_to_end(self):
        selector = 'span.ant-tabs-tab-next'
        span_next = self._get_web_element().find_element(By.CSS_SELECTOR, selector)
        if span_next:
            while 'ant-tabs-tab-btn-disable' not in span_next.get_attribute('class'):
                ElementFunction(self._driver).click(span_next)

    # 暂未使用
    def _find_tab_element(self, value):
        selector = './/div[@role="tab" and normalize-space(text())="{0}"]'.format(value)
        parent_element = self._get_web_element()
        try:
            return parent_element.find_element(By.XPATH, selector)
        except NoSuchElementException:
            return None

    def _find_tab_elements(self):
        parent_element = self._get_web_element()
        selector = 'div[role="tab"]'
        return parent_element.find_elements(By.CSS_SELECTOR, selector)

    def _get_tab_title(self, element):
        title = element.text
        return title.strip()

    def _is_checked(self, element):
        value = element.get_attribute('aria-selected')
        return True if value and value == 'true' else False

    def get_identification(self):
        identification = {'class': ['ant-tabs', 'ant-tabs-nav', 'ant-tabs-bar']}
        return identification

